#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from EU.admin.StatusCode import StatusCode
from EU.models import Administrator
from EU.admin.CheckCode import create_validate_code
from io import  BytesIO
import json
__author__ = "Yunpeng Li <ypli.chn@outlook.com.com>"

def admin_login(username,password,code,correct_code):
    _dict = {}

    try:
        if code.lower() == correct_code.lower():
            booladmin = Administrator.objects.filter(username__exact = username,password__exact = password)
            print(booladmin)
            if booladmin:
                status = StatusCode.Success
                message = '登录成功'
            else:
                status = StatusCode.PasswordError
                message = '用户不存在或密码错误'
        else:
            status = StatusCode.CheckCodeError
            message = '验证码错误'
    #数据库的exceptisudoon

    except BaseException as e:
        status = StatusCode.UnknowError
        message = '未知错误'
        print('exception:',e)

    _dict['status'] = status
    _dict['message'] = message
    return _dict

def get_check_code():
    mstream = BytesIO()
    img,validate_code = create_validate_code()
    img.save(mstream, 'jpeg')
    return validate_code,mstream.getvalue()


def admin_update_password(username,old_password,new_password,confirm_password):
    _dict = {}
    try:
        booladmin = Administrator.objects.filter(username__exact = username,password__exact = old_password)

        if booladmin:
            if (new_password == confirm_password):
                Administrator.objects.filter(username = username).update(password = new_password)
                status = StatusCode.Success
                message = '修改成功'
            else:
                status = StatusCode.NewPwdError
                message = '两次密码输入不一致,请重新输入'
        else:
            status = StatusCode.PasswordError
            message = '用户不存在或密码错误'

    except BaseException as e:
        status = StatusCode.UnknowError
        message = '错误'
        print('e',e)
    #测试

    _dict['status'] = status
    _dict['message'] = message
    return json.dumps(_dict)

def check_admin(username):
    admin = None
    try:
        admin = Administrator.objects.get(username=username)
    except Exception as e:
        pass

    if admin != None:
        return True
    return False
    pass
